package spark.graphics.scenegraph;

import spark.math.Vector2;
import spark.graphics.Renderer;
import spark.graphics.ISpriteRenderable;

import javax.media.opengl.GL;
import java.util.LinkedList;

public class SpriteNode extends SceneGraphNode {
	private LinkedList<ISpriteRenderable> spriteRenderables;

	public LinkedList<ISpriteRenderable> getRenderables() {
		if(spriteRenderables == null) {
			spriteRenderables = new LinkedList<ISpriteRenderable>();
		}
		return spriteRenderables;
	}

	public SpriteNode registerForRendering(ISpriteRenderable spriteRenderable) {
		getRenderables().add(spriteRenderable);
		return this;
	}

	@Override
	void render() {
		renderSprites();
		for(SceneGraphNode child : getChildren()) {
			child.render();
		}
	}

	private void renderSprites() {
		if(spriteRenderables == null) {
			return;
		}
		for(ISpriteRenderable spriteRenderable : spriteRenderables) {
			Vector2 dimensions = spriteRenderable.getDimensions();
			float left = -dimensions.x / 2;
			float right = -left;
			float top = dimensions.y / 2;
			float bottom = -top;

			Vector2 uv = spriteRenderable.getSprite().getUvCoordinates();
			Vector2 textureDimensions = spriteRenderable.getSprite().getDimensions();
			float uvLeft = uv.x;
			float uvRight = uv.x + textureDimensions.x;
			float uvTop = uv.y;
			float uvBottom = uv.y + textureDimensions.y;

			spriteRenderable.getSprite().getTexture().bind();
			Renderer.getInstance().getGl().glBegin(GL.GL_QUADS);
			Renderer.getInstance().getGl().glTexCoord2f(uvLeft, uvBottom);
			Renderer.getInstance().getGl().glVertex3f(left, bottom, 0);

			Renderer.getInstance().getGl().glTexCoord2f(uvRight, uvBottom);
			Renderer.getInstance().getGl().glVertex3f(right, bottom, 0);

			Renderer.getInstance().getGl().glTexCoord2f(uvRight, uvTop);
			Renderer.getInstance().getGl().glVertex3f(right, top, 0);

			Renderer.getInstance().getGl().glTexCoord2f(uvLeft, uvTop);
			Renderer.getInstance().getGl().glVertex3f(left, top, 0);
			Renderer.getInstance().getGl().glEnd();
		}
	}
}